import Taro from '@tarojs/taro';
import React, { Component } from 'react';
import { View, Image, Video, Canvas } from '@tarojs/components';
import config from '@/service/config';
import addImg from '@/assets/image/upload/my_camera.png'
// import { ImageUpload } from "@/services/tyre/tyre"
import * as sdk from 'api/fetch';
import moment from 'dayjs';
import './choose-view.scss';
export default class ChooseImageView extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      ...props,
      backData: JSON.stringify(props.files), ///备份数据
      canvasWidth: 500,
      canvasHeight: 375,
    };
    this.checkImage();
  }

  componentDidUpdate() {
    const { files } = this.props;
    /// 比较数据是否相同 相同则不刷新数据
    let { backData } = this.state;
    if (JSON.stringify(this.props.files) == backData) {
      return;
    }
    backData = JSON.stringify(this.props.files);
    let that = this;
    this.setState(
      {
        files,
        backData,
      },
      () => {
        that.checkImage();
      },
    );
  }

  onImageClick = (data) => {
    let that = this;
    if (data.isAdd) {
      ///查询当前已经有多少张图片
      const { files, maxCount } = this.state;
      const count = maxCount - files.length + 1;
      Taro.chooseMedia({
        count: count, // 默认9
        mediaType: ['mix'],
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
        camera: 'back',// 默认拉起后置摄像头
        maxDuration: 15, // 选择视频最大时长
        success: async function (res) {
          if (res.tempFiles?.[0]?.fileType == 'video') {//选择的为视频
            if (res.tempFiles[0].duration > 15) {
              Taro.showToast({
                title: '视频超过15秒',
                icon: 'error',
                duration: 2000
              })
              return
            }
            // 将选中的视频存在files中
            var tmpFileList = res.tempFiles.map((file) => {
              return {
                url: file.tempFilePath,
              };
            });
            // 发起网络请求 将tag有值的数据进行上传 如果上传成功则移除tag值
            // 获取上传Token
            let { data } = await sdk.rzget('oss/sign', {});
            const successFiles = await (
              await that.uploadFile(tmpFileList, data.accessid, data.policy, data.signature)
            )
              .filter((item) => item.status === 'success')
              .map((item) => {
                delete item.status;
                delete item.tag;
                return item;
              });

            // 成功的数量<=0则不在走下面流程
            if (successFiles && successFiles.length <= 0) return;

            // 保存files的值并通知外部刷新数据源
            await that.checkImage(successFiles, true);

          } else {//选择的为图片
            // 将选中的图片存在files中
            var tmpFileList = res.tempFiles.map((file) => {
              return {
                url: file.tempFilePath,
              };
            });

            // 发起网络请求 将tag有值的数据进行上传 如果上传成功则移除tag值
            // 获取上传Token
            let { data } = await sdk.rzget('oss/sign', {});
            const successFiles = await (
              await that.uploadFile(tmpFileList, data.accessid, data.policy, data.signature)
            )
              .filter((item) => item.status === 'success')
              .map((item) => {
                delete item.status;
                delete item.tag;
                return item;
              });

            // 成功的数量<=0则不在走下面流程
            if (successFiles && successFiles.length <= 0) return;

            // 保存files的值并通知外部刷新数据源
            await that.checkImage(successFiles, true);

          }
        },
      });
    } else {
      const { files } = this.state;
      this.previewImage(data.url, files);
    }
  };

  /// 单个图片压缩
  compressfile = async (file) => {
    let that = this;
    return new Promise((resolve, reject) => {
      /// 压缩图片  图片小于300k直接上传 如果大于300k则压缩图片大小
      const maxSize = 300 * 1024;
      const fileSize = file.size;
      if (fileSize > maxSize) {
        Taro.getImageInfo({
          src: file.path,
          success: async (data) => {
            //---------利用canvas压缩图片--------------
            var canvasWidth = data.width; //图片原始长宽
            var canvasHeight = data.height;
            // if (canvasWidth > 500) {
            //   canvasWidth = 500;
            //   canvasHeight = canvasHeight / (data.width / 500);
            // }
            let interval = 500;
            /// 时间处理 根据图片大小 在导出图片时延时一定时间后开始处理返回数据，防止数据未导出成功
            const kb = fileSize / 1000;
            if (kb < 1000) {
              interval = 500;
            } else {
              interval = kb / 20;
            }

            //----------绘制图形并取出图片路径--------------
            var ctx = Taro.createCanvasContext('myCanvas');
            ctx.drawImage(file.path, 0, 0, canvasWidth, canvasHeight);
            ctx.draw(
              false,
              // @ts-ignore
              setTimeout(() => {
                Taro.canvasToTempFilePath({
                  canvasId: 'myCanvas',
                  destWidth: canvasWidth,
                  destHeight: canvasHeight,
                  success: async function (data1) {
                    console.log(data1.tempFilePath, '<<<<<<SUCCESS');
                    resolve({
                      path: data1.tempFilePath,
                    });
                  },
                  fail: function (data1: any) {
                    // 压缩失败时上传基础缓存
                    console.log('压缩失败时上传基础缓存');
                    resolve({
                      path: file.path,
                    });
                  },
                });
              }, interval),
            );
          },
        });
      } else {
        resolve(file);
      }
    });
  };

  /// 图片压缩
  compressfiles = async (uploadFiles = []) => {
    let that = this;
    let files = [];
    const count = uploadFiles?.length || 0;
    Taro.showLoading({
      title: '压缩中...',
    });

    return new Promise(async (resolve, reject) => {
      for (let index = 0; index < count; index++) {
        const file = uploadFiles[index];
        const res = await this.compressfile(file);
        console.log(index);
        files.push(res);
        if (index === count - 1) {
          Taro.hideLoading();
          resolve(files);
        }
      }
    });
  };

  /// 发起图片上传 异步上传
  uploadFile = async (uploadFiles = [], accessid, policy, signature) => {
    Taro.showLoading({
      title: '上传中',
    });
    // let accessId = "LTAI5tHSDf1rq5xdCjFX1ViK"
    // let policy = "eyJleHBpcmF0aW9uIjoiMjAyMy0wNC0wNlQwNzoyODoxNS4wNTJaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCJpdHNvdXJjZSJdXX0="
    // let signature = "diR7fQncqdeWdVDVuEapP+gf5Qs="
    const promises = uploadFiles.map((data) => {
      return new Promise((resolve, reject) => {
        Taro.uploadFile({
          url: config.ossHost,
          filePath: data.url,
          name: 'file', // 必须填file。
          formData: {
            OSSAccessKeyId: accessid,
            policy,
            signature,
            key: `itsource/${data.url.slice(data.url.length / 2)}`,
            // 'x-oss-security-token': securityToken // 使用STS签名时必传。
          },
          success: (res) => {
            if (res.statusCode === 204) {
              data.status = 'success';
              data.url = `${config.ossHost}/itsource/${data.url.slice(data.url.length / 2)}`;
              resolve(data);
            }
          },
          fail: (err) => {
            console.log(err);
            Taro.showToast({
              title: '上传失败',
              icon: 'none',
              mask: true,
            });
            /// 上传失败
            data.status = 'fail';
            resolve(data);
          },
        });
      });
    });
    const list = await Promise.all(promises);
    Taro.hideLoading();
    return list;
  };

  checkImage = async (tmpFileList = [], noti = false) => {
    return new Promise((resolve) => {
      ///1.拿到已经选中的file列表
      let { files, maxCount, mode } = this.state;
      ///2.移除之前的addFile
      const newFiles = files.filter((item, index) => {
        return item.isAdd !== true;
      });

      ///3.合并列表
      if (tmpFileList && tmpFileList.length > 0) {
        newFiles.push(...tmpFileList);
      }

      ///4.数据返回上级
      if (this.props.onFileChange && noti) {
        this.props.onFileChange(newFiles);
      }

      ///5.判断新的addFile
      files = JSON.parse(JSON.stringify(newFiles));
      if (files.length < maxCount && mode === 'add') {
        /// 添加add按钮
        files.push(this.addFile());
      }
      /// 更新数据会有延迟 setTimeout来解决页面已经刷新 数据还没有变更过来的问题
      setTimeout(() => {
        this.setState(
          {
            files,
          },
          () => {
            resolve(true);
          },
        );
      }, 0);
    });
  };

  addFile = () => {
    return {
      url: addImg,
      isAdd: true,
    };
  };

  /// 点击删除
  onDeleteImage = (data) => {
    const { files } = this.state;
    const newFiles = files.filter((item) => {
      return item.url != data.url;
    });
    this.setState(
      {
        files: newFiles,
      },
      () => {
        this.checkImage([], true);
      },
    );
  };

  previewImage = (img, files) => {
    const imgs = files
      .filter((data) => {
        return !data.isAdd;
      })
      .map((item) => {
        return item.url;
      });
    Taro.previewImage({
      current: img, // 当前显示图片的http链接
      urls: imgs, // 需要预览的图片http链接列表
    });
  };

  render() {
    const { files, mode } = this.state;
    const imgReg = /^https?:\/\/(.+\/)+.+(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i;
    const videoReg = /^https?:\/\/(.+\/)+.+(\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb|mp4))$/i;
    return (
      <View className="chooseImageView">
        <View className="choose-img-wrap">
          {files.map((data) => {
            return (
              <View className="img-container">
                {
                  data.url && imgReg.test(data.url) ?//图片
                    <Image
                      className="img"
                      key={data.url}
                      onClick={this.onImageClick.bind(this, data)}
                      src={data.url}
                      mode={data.isAdd ? 'aspectFit' : 'aspectFill'}
                    /> : data.url && videoReg.test(data.url) ? //视频
                      <Video
                        className="img"
                        // onClick={this.onImageClick.bind(this, data)}
                        src={data.url}
                        initialTime={0}
                        controls={true}
                        autoplay={false}
                        loop={false}
                        muted={false}
                      /> :
                      <Image
                        className="img"
                        onClick={this.onImageClick.bind(this, data)}
                        mode="widthFix"
                        src={addImg} />
                }
                {!(data.isAdd || data.isDefault) && mode === 'add' && (
                  <View className="img-delete" onClick={this.onDeleteImage.bind(this, data)}>
                    删除
                  </View>
                )}
                {data.isDefault && <Image className="img" mode="widthFix" src={addImg} />}
              </View>
            );
          })}
        </View>
      </View>
    );
  }
}

// @ts-ignore
ChooseImageView.defaultProps = {
  mode: 'add', /// 显示模式 新增/详情   add | detail
  files: [], /// 图片列表
  maxCount: 9, ///最多上传张数
};
